<?php
/**
 * Created by PhpStorm.
 * User: cx
 * Date: 2018/12/5
 * Time: 14:56
 */

namespace app\admin\controller;
use app\admin\model\Message as MessageModel;
class Message  extends Common
{
   public function _initialize()
   {
       parent::_initialize();
       $this->cModel = new MessageModel();
   }

    public function index()
    {
        $where = [];
        if (input('get.search')){
            $where['info'] = ['like', '%'.input('get.search').'%'];
        }
        $order = 'id desc';
        $field = 'id,info';
        $dataList = $this->cModel->where($where)->order($order)->field($field)->paginate('', false, page_param());
        $this->assign('dataList', $dataList);
        return $this->fetch();
    }

    public function create()
    {
        if (request()->isPost()){
            $data = input('post.');
            $data['create_time'] = time();
            $result = $this->cModel->validate(CONTROLLER_NAME.'.add')->allowField(true)->save($data);
            if ($result){
                return ajaxReturn(lang('action_success'), url('index'));
            }else{
                return ajaxReturn($this->cModel->getError());
            }
        }else{
            return $this->fetch('edit');
        }
    }

    public function edit($id)
    {
        if (request()->isPost()){
            $data = input('post.');
            $data['update_time'] = time();
            $result = $this->cModel->validate(CONTROLLER_NAME.'.edit')->allowField(true)->save($data, $data['id']);
            if ($result){
                return ajaxReturn(lang('action_success'), url('index'));
            }else{
                return ajaxReturn($this->cModel->getError());
            }
        }else{
            $data = $this->cModel->get($id);
            $this->assign('data', $data);
            return $this->fetch();
        }
    }

    public function delete()
    {
        if (request()->isPost()){
            $id = input('id');
            if (isset($id) && !empty($id)){
                $id_arr = explode(',', $id);
                $where = [ 'id' => ['in', $id_arr] ];
                $result = $this->cModel->where($where)->delete();
                if ($result){
                    return ajaxReturn(lang('action_success'), url('index'));
                }else{
                    return ajaxReturn($this->cModel->getError());
                }
            }
        }
    }
}